#	m42-xmas-memory
#   Copyright (C) 2014  Jannik Haberbosch
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.


import pygame
pygame.init()

from code.classes.EnableDisableOptionImage import EnableDisableOptionImage


class EnableDisableOption( pygame.sprite.Sprite ):
	def __init__( self, button, db_conn, db_cursor, db_table, db_table_column ):
		pygame.sprite.Sprite.__init__( self )

		self.button = button
		self.db_conn = db_conn
		self.db_cursor = db_cursor
		self.db_table = db_table
		self.db_table_column = db_table_column

		self.option_value = self.get_option_value()

		self.image = button.image
		self.rect = button.rect

		self.enable_disable_option_image = EnableDisableOptionImage(
			self.option_value,
			( self.rect.right + 50, self.rect.centery )
		)


	def update( self ):
		if self.button.update() is not False:
			self.set_option_value()
			self.option_value = self.get_option_value()
			self.enable_disable_option_image.set_state( self.option_value )
			self.enable_disable_option_image.flip_image()

			self.image = self.button.image
			self.rect = self.button.rect

			return True

		self.image = self.button.image
		self.rect = self.button.rect
		return False

		


	def get_option_value( self ):
		self.db_cursor.execute(
			"SELECT %s FROM %s" % ( self.db_table_column, self.db_table )
		)
		result = self.db_cursor.fetchone()
		
		if result[self.db_table_column] == 1:
			return True
		else:
			return False


	def set_option_value( self ):
		if self.option_value:
			value = 0
		else:
			value = 1
		
		self.db_cursor.execute(
			"UPDATE %s SET %s = %d" % ( self.db_table, self.db_table_column, value )
		)
		self.db_conn.commit()
